/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

package com.huaweicloud.haydn.delivercore.agent.utils;

import com.huaweicloud.haydn.delivercore.agent.common.exception.BusinessErrorEnum;
import com.huaweicloud.haydn.delivercore.agent.common.exception.BusinessException;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 功能描述
 *
 * @since 2023-09-05
 */
@Configuration
@ConditionalOnProperty("encrypt.key")
public class EncryptUtil {
    static PooledPBEStringEncryptor encryptor;

    @Bean
    public PooledPBEStringEncryptor getEncryptor(@Value("${encrypt.key}") String key) {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(key);
        config.setAlgorithm("PBEWithMD5AndDES");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        EncryptUtil.encryptor = encryptor;
        return encryptor;
    }

    static public String decrypt(String s) {
        if (encryptor == null) {
            throw new BusinessException(BusinessErrorEnum.ENCRYPTOR_ERROR);
        }
        return encryptor.decrypt(s.substring(4));
    }
}
